package com.yang.system.application.orgMng.empService;

import com.yang.system.domain.common.exception.BusinessException;
import com.yang.system.domain.orgMng.emp.Emp;
import com.yang.system.domain.orgMng.emp.EmpRepository;
import org.springframework.transaction.annotation.Transactional;

public class EmpService {
    private final EmpRepository empRepository;
    private final EmpAssembler assembler;
    private final EmpUpdator updator; //用于修改Emp聚合


    public EmpService(EmpRepository empRepository
            , EmpAssembler assembler, EmpUpdator updator) {
        this.empRepository = empRepository;
        this.assembler = assembler;
        this.updator = updator;
    }

    @Transactional
    public EmpResponse addEmp(CreateEmpRequest request, User user) {
        Emp emp = assembler.fromCreateRequest(request, user);

        empRepository.save(emp);
        return assembler.toResponse(emp);
    }
    @Transactional
    public EmpResponse updateEmp(Long empId, UpdateEmpRequest request
            , User user) {
        Emp emp = (Emp) empRepository.findById(request.getTenantId(), empId)
                .orElseThrow(() -> new BusinessException("Emp id(" + empId + ") 不正确！"));

        updator.update(emp, request, user);

        // 这里增加了判断
        if(!empRepository.save(emp)) {
            throw new BusinessException(
                    "这个员工已经被其他人同时修改了，请重新修改！");
        };
        return assembler.toResponse(emp);
    }
}
